package jrobutt.room;

import jrobutt.*;

import java.util.*;
import java.awt.*;
import java.util.List;

public class ExplosionParticleEmitter extends MultiUpdatableAndRenderable
{
    private List<Particle> particles;
    private List<Particle> cached_next_particles;
    
    public GameSprite particle_sprite;
    
    protected Collection<? extends Updatable> get_updatable_children ()
    {
        return particles;
    }
    protected Collection<? extends Renderable> get_renderable_children ()
    {
        return particles;
    }
    
    public ExplosionParticleEmitter (GameSprite particle_sprite)
    {
        particles = new ArrayList<Particle>();
        cached_next_particles = new ArrayList<Particle>();
        
        this.particle_sprite = particle_sprite;
    }
    
    public void explodeAt (float x, float y)
    {
        for (int k=0; k<12; k++)
        {
            float angle = (float)Math.random() * GameMath.TwoPi;
            float life = 5.0f + (float)Math.random() * 10.0f;
            float speed = 4.0f + (float)Math.random() * 4.0f;
            float xspeed = speed * (float)Math.cos(angle);
            float yspeed = speed * (float)Math.sin(angle);
            particles.add(new Particle(x, y, xspeed, yspeed, -xspeed/life / 2.0f, -yspeed/life / 2.0f, life, particle_sprite));
        }
    }
    
    public void update ()
    {
        super.update();
        
        cached_next_particles.clear();
        
        for (Particle particle : particles)
        {
            if (!particle.is_dead)
            {
                cached_next_particles.add(particle);
            }
        }
        
        // swap `particles` and `cached_next_particles`
        List<Particle> temp = particles;
        particles = cached_next_particles;
        cached_next_particles = temp;
    }
}
